package com.ys.peony.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseFragment;
import com.ys.peony.enums.SwipeDirect;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.interfaces.MyItemClickListener;
import com.ys.peony.model.BusiTypeFileModel;
import com.ys.peony.model.JiekuanrenModel;
import com.ys.peony.model.VehicleTypeModel;
import com.ys.peony.ui.activity.BusiLoanInfoActivity;
import com.ys.peony.ui.activity.ShowImageActivity;
import com.ys.peony.ui.activity.TakePicturesActivity;
import com.ys.peony.ui.adapter.ClientPicAdapter;
import com.ys.peony.ui.widget.AlertTwoBtnDialog;
import com.ys.peony.ui.widget.CustomAlertDialogCallBack;
import com.ys.peony.ui.widget.Divider;
import com.ys.peony.ui.widget.PicTypePicker;
import com.ys.peony.ui.widget.TipAlertDialog;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 描述：资料上传功能
 * authro：yukang
 * time:2017/09/18
 */

@SuppressLint("ValidFragment")
public class ClientPicFragment<T> extends BaseFragment implements View.OnClickListener, PicTypePicker.PicTypeCallBack
        , MyItemClickListener.ClientItemListener {

    @BindView(R.id.takepic_btn)
    Button takePicBtn;
    @BindView(R.id.client_title)
    TextView titleTv;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerview;

    private String fileType = "1";//1:借款人资料  2:补件资料  3:打回补件资料
    private int mPageType = YSConstant.INVALID;
    private PicTypePicker picTypePicker;
    private List<T> mList = new ArrayList<>();
    private List<BusiTypeFileModel> mDataList = new ArrayList();
    private List<BusiTypeFileModel> mTypeList;
    private ClientPicAdapter mAdapter;
    private JiekuanrenModel loanModel;
    private LinearLayoutManager mLayoutManager;

    public ClientPicFragment(JiekuanrenModel loanModel, String fileType, int pageType) {
        this.loanModel = loanModel;
        this.fileType = fileType;
        this.mPageType = pageType;
    }

    @Override
    public int getLayoutRes() {
        return R.layout.frament_client_pic;
    }

    @Override
    public void initView() {
        onInitData();
        initAdatper();

    }

    private void initAdatper() {
        mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mAdapter = new ClientPicAdapter(getContext(), mDataList, this);
        mRecyclerview.addItemDecoration(new Divider(getContext()));
        mRecyclerview.setLayoutManager(mLayoutManager);
        mRecyclerview.setAdapter(mAdapter);
    }

    private void onInitData() {
        takePicBtn.setOnClickListener(this);
        if (mPageType == BusiLoanInfoActivity.PAGE_CLIENT) {
            titleTv.setText(loanModel.getClientName() + "的授信资料列表");
        } else if (mPageType == BusiLoanInfoActivity.PAGE_VEHICLE) {
            titleTv.setText("抵押物的授信资料列表");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.takepic_btn:
                if ("1".equals(fileType) && !"0".equals(loanModel.getLoanStatus()) && !"5".equals(loanModel.getLoanStatus()) && !"7".equals(loanModel.getLoanStatus())) {
                    TipAlertDialog dialog = new TipAlertDialog(getActivity());
                    dialog.setMessage(getResources().getString(R.string.loan_file_operation_tip));
                    return;
                }
                if (mTypeList == null || mTypeList.size() < 1) {
                    ToastUtils.showToast("没有获取到授信类型");
                    return;
                }
                if (picTypePicker == null) {
                    picTypePicker = new PicTypePicker(getActivity(), this);
                }
                picTypePicker.show(takePicBtn, mTypeList);
                break;
        }
    }

    @Override
    public void picTypeItemOnclick(final BusiTypeFileModel model) {
        goToTakePicActivity(model);
    }

    private void goToTakePicActivity(BusiTypeFileModel model) {
        Intent it = new Intent(getActivity(), TakePicturesActivity.class);
        it.putExtra("busiTypeFileModel", model);
        it.putExtra("fileType", fileType);
        it.putExtra("loanId", loanModel.getId());
        it.putExtra("patchId", loanModel.getPatchId());
        this.startActivityForResult(it, YSConstant.ACTIVITY_TAKE_PIC);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == YSConstant.ACTIVITY_TAKE_PIC && resultCode == Activity.RESULT_OK) {
            ((BusiLoanInfoActivity) getActivity()).getUploadedFiles();
        }
    }

    /**
     * @param list
     */
    public void setUploadedFileList(List<T> list) {
        this.mList = list;
        mDataList.clear();
        if (mList != null && mList.size() > 0) {
            switch (mPageType) {
                case BusiLoanInfoActivity.PAGE_CLIENT:
                    mDataList.addAll((List<BusiTypeFileModel>) mList);
                    break;
                case BusiLoanInfoActivity.PAGE_VEHICLE:
                    VehicleTypeModel vehicleTypeModel = ((List<VehicleTypeModel>) mList).get(0);
                    if (vehicleTypeModel != null) {
                        mDataList.addAll(vehicleTypeModel.getRiskInfoList());
                    }
                    break;
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    public void setTypeList(List<BusiTypeFileModel> list) {
        mTypeList = list;
    }

    @Override
    public void onImgClick(String path) {
        if (!TextUtils.isEmpty(path)) {
            Bundle bundle = new Bundle();
            bundle.putString(ShowImageActivity.IMG_URL, path);
            skipToTargetPage(ShowImageActivity.class, bundle);
        }
    }

    @Override
    public void onImgLongClick(long id, int position1, int position2) {
        delPicFile(id, position1, position2);
    }

    public void delPicFile(final long id, final int position1, final int position2) {
        AlertTwoBtnDialog dialog = new AlertTwoBtnDialog(getContext(), new CustomAlertDialogCallBack() {
            @Override
            public void onCancelBtnClicked() {
            }

            @Override
            public void onSureBtnClicked() {
                delFileToIntent(id, position1, position2);
            }

            @Override
            public void onSureBtnClicked1(String editStr) {
            }
        });
        dialog.setMessage("确定删除图片吗？");
    }

    /**
     * 描述：删除图片资料
     *
     * @param fileId:图片资料id
     */
    private void delFileToIntent(final long fileId, final int position1, final int position2) {
        LoadingProgressUtils.showProgressDialog(getContext());
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Long.parseLong(SharePreferencesUtils.getInstance().getUserModel().getId()));//(必传) Long  用户主键
        params.put("busiLoanInfoId", fileId);//(必传) Long 业务主键
        httpManager.get(HttpURL.deleteBusiLoanInfo, params, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                if (mDataList.get(position1).getFiles().size() > 0) {
                    mDataList.get(position1).getFiles().remove(position2);
                }
                if (mDataList.get(position1).getFiles().size() > 0) {
                    mAdapter.notifyItemChanged(position1);
                } else {
                    mDataList.remove(position1);
                    mAdapter.notifyItemRemoved(position1);
                    mAdapter.notifyItemRangeChanged(0, mDataList.size());
                }

            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
            }
        });
    }
}
